package com.butterfly.hotkey.worker.framework.netty.server;

import com.butterfly.hotkey.core.constant.Constants;
import com.butterfly.hotkey.worker.util.SystemUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

import static com.butterfly.hotkey.core.constant.Constants.DELIMITER;
import static com.butterfly.hotkey.core.constant.Constants.MAX_LENGTH;

/**
 * 启用后用于业务服务连接用
 *
 * @author butterfly
 */
public class WorkerNettyServer {

    private static final Logger log = LoggerFactory.getLogger(Constants.WORKER);

    public void startNettyServer(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(SystemUtil.idealWorkerCount());
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChildChannelHandler());
            ChannelFuture future = bootstrap.bind(port).sync();
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                bossGroup.shutdownGracefully(1000, 3000, TimeUnit.MILLISECONDS);
                workerGroup.shutdownGracefully(1000, 3000, TimeUnit.MILLISECONDS);
            }));
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("worker netty start failed", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class ChildChannelHandler extends ChannelInitializer<Channel> {

        @Override
        protected void initChannel(Channel ch) {
            WorkerChannelHandler serverHandler = new WorkerChannelHandler();
            ByteBuf delimiter = Unpooled.copiedBuffer(DELIMITER.getBytes());
            ch.pipeline()
                    .addLast(new DelimiterBasedFrameDecoder(MAX_LENGTH, delimiter))
                    .addLast(new StringDecoder())
                    .addLast(new StringEncoder())
                    .addLast(serverHandler);
        }
    }

}
